<?php
session_start();
if(!isset($_GET['step']))
{
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $port = $_POST['port'];
        if(!empty($port))
            $ip = $_POST['ip'] . ':' . $port;
        else
            $ip = $_POST['ip'];
        $user = $_POST['user'];
        $password = $_POST['password'];
        $conn = @mysql_connect($ip, $user, $password);
        if(!mysql_errno())
        {
            $_SESSION['ip'] = $ip;
            $_SESSION['user'] = $user;
            $_SESSION['password'] = $password;
            header('Location:?step=2');
        }
        else
        {
            $var['error'] = 'Fail: 请检查数据库填写信息是否有误!';
            extract($var);
        }
    }
    require 'step1.php';
}
else if($_GET['step'] == 2)
{
    $conn = mysql_connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['password']);
    $query = mysql_query("SHOW DATABASES", $conn);
    $databases = array();
    $tables = array();

    while($row = mysql_fetch_row($query))
    {
        $databases[] = $row[0];
    }

    $var['databases'] = $databases;

    if(isset($_GET['database']))
    {
        mysql_select_db($_GET['database']);
        $query = mysql_query("SHOW TABLES");

        while($row = mysql_fetch_row($query))
        {
            $tables[] = $row[0];
        }

        $var['tables'] = $tables;
    }

    extract($var);
    require 'step2.php';
}
else if($_GET['step'] == 3)
{
    if(!isset($_POST['tables']) || empty($_POST['tables']))
    {
        $var['error'] = '没有任何数据表被选择';
    }
    else
    {
        $conn = mysql_connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['password']);
        $tables = $_POST['tables'];
        mysql_select_db($_POST['database']);
        $content = array();

        foreach($tables as $k => $item)
        {
            $query = mysql_query("SHOW FULL COLUMNS FROM $item", $conn);
            while($row = mysql_fetch_row($query))
            {
                $row[1] = preg_replace('/\s+/', ',', $row[1]);
                $tmp = explode(',', $row[1]);
                $content[$item][$row[0]]['type'] = $tmp[0];
                $content[$item][$row[0]]['attr'] = isset($tmp[1]) ? $tmp[1] : '';
                $content[$item][$row[0]]['is_null'] = $row[3];
                $content[$item][$row[0]]['default'] = $row[5];
                $content[$item][$row[0]]['is_pri'] = $row[4];
                $content[$item][$row[0]]['extra'] = $row[6];
                $content[$item][$row[0]]['zs'] = $row[8];
            }
        }

        $var['content'] = $content;
    }
    extract($var);
    require 'step3.php';
}
